﻿Imports HTLibrary
Imports TNCBAL
Imports TNCDAL

Public Class ucFileContTransport
    Private _objContController As CContainerController 'ContRepository
    Private _objFile As tblFile ' Thông tin File
    Private _objCont As tblCont
    'User control
    'Private _ucContTransportCharges As ucContTransportCharges

    Public Sub New(ByVal obj As tblFile)
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(dataGridViewXFileContainer)
        'Lưu thông tin File
        _objFile = obj
        _objContController = New CContainerController(GeneralClassDAL.dc)
        InitCommands()
    End Sub

    Private Sub ucFileContTransport_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        InitData()
        BindingDataGridView(_objFile)
        FormatDataGridView()
    End Sub

    ''' <summary>
    ''' Khởi tạo dữ liệu mặc định trên form
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub InitData()
        'Dim objDriverController As New MDrivers(GeneralClassDAL.dc)
        'cmbDriver.ValueMember = "ID_Driver"
        'cmbDriver.DisplayMember = "DriverName"
        ''cmbDriver.DataSource = GeneralClassDAL.dc.tblDrivers
        'cmbDriver.DataSource = objDriverController.getDriversList1()
        CViewer.BindDriversToComboBox(cmbDriver)

        CViewer.BindDemDetToComboBox(cmbKhoDongGiaoHang)
        'Dim objDemDet As New DemDetController
        'cmbKhoDongGiaoHang.ValueMember = "ID_DemDet"
        'cmbKhoDongGiaoHang.DisplayMember = "DemDetName"
        'cmbKhoDongGiaoHang.DataSource = objDemDet.SelectAllRecord()

        CViewer.BindDemDetToComboBox(cmbKhoGiaoHang)
        'cmbKhoGiaoHang.ValueMember = "ID_DemDet"
        'cmbKhoGiaoHang.DisplayMember = "DemDetName"
        'cmbKhoGiaoHang.DataSource = objDemDet.SelectAllRecord()
    End Sub

    ''' <summary>
    ''' Hiển thị chi tiết Thông tin vận chuyển trên form
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub FillContDetails()
        Try
            txtContNo.Text = _objCont.ContNo
        Catch ex As Exception
            txtContNo.Text = ""
        End Try

        Try
            lblNoiHaCont.Text = _objFile.tblPort.Port
        Catch ex As Exception
            lblNoiHaCont.Text = ""
        End Try

        Try
            lblNoiNangCont.Text = _objFile.tblPort1.Port
        Catch ex As Exception
            lblNoiNangCont.Text = ""
        End Try


        Try
            dtHaCont.Value = _objCont.GetEmptyContDate.Value
        Catch ex As Exception
            dtHaCont.Value = Nothing
        End Try


        Try
            dtNangCont.Value = _objCont.ReturnContDate.Value
        Catch ex As Exception
            dtNangCont.Value = Nothing
        End Try


        'Hiển thị Driver
        Try
            cmbDriver.SelectedValue = _objCont.tblDriver.ID_Driver
        Catch ex As Exception
            cmbDriver.Text = ""
            cmbDriver.SelectedIndex = -1
        End Try

        'Hiển thị Vessel
        Try
            cmbKhoDongGiaoHang.SelectedValue = _objCont.tblDemDet.ID_DemDet
        Catch ex As Exception
            cmbKhoDongGiaoHang.Text = ""
            cmbKhoDongGiaoHang.SelectedIndex = -1
        End Try

    End Sub

#Region "Cont Fee"
    'Public Sub InitContChargesDataGridView(ByVal objCont As tblCont)
    '    _ucContTransportCharges = New ucContTransportCharges(objCont)
    '    _ucContTransportCharges.Dock = DockStyle.Fill
    '    PanelExContFee.Controls.Add(_ucContTransportCharges)
    '    '_ucContTransportCharges.dataGridViewXTransportCharges_CurrentCellChangedEvent = New EventHandler(AddressOf dataGridViewXFileMBL_CurrentCellChanged)
    '    _ucContTransportCharges.BindDataGridView()
    'End Sub

    Private Sub dataGridViewXFileContainer_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dataGridViewXFileContainer.CurrentCellChanged
        Try
            If _ucCommands Is Nothing Then
                Return
            End If

            If _ucCommands.btnUpdate.Enabled Then
                Return
            End If

            If dataGridViewXFileContainer.CurrentCell IsNot Nothing Then
                _objCont = _objContController.SelectRecordByID(dataGridViewXFileContainer.Rows(dataGridViewXFileContainer.CurrentCell.RowIndex).Cells("Id_Cont").Value)
                '_objCont = _objContController.SelectRecordById(dataGridViewXFileContainer.Rows(dataGridViewXFileContainer.CurrentCell.RowIndex).Cells("Id_Cont").Value)
                FillContDetails()
                'InitContChargesDataGridView(objCont)

                'Sỹ code
                If Not uc Is Nothing Then
                    uc.KhoiTaodtgContFee(_objCont.ID_Cont)
                End If
            End If
        Catch ex As Exception
#If DEBUG Then
            Throw ex
#Else
            MessageBox.Show(ex.Message)
#End If
        End Try
    End Sub
#End Region

#Region "DataGridView"
    Public Sub FormatDataGridView()
        CViewer.FormatDataGridView(dataGridViewXFileContainer)
    End Sub

    Public Sub BindingDataGridView(ByVal obj As tblFile, Optional ByVal indexRow As Integer = -1)
        'Lưu thông tin File
        _objFile = obj
        Dim query As IQueryable
        If _objFile IsNot Nothing Then
            query = _objContController.SelectContsByTransport(_objFile.ID_File)
        Else
            query = _objContController.SelectContsByTransport(-1)
        End If

        If indexRow > 0 Then
            'Set current row
            dataGridViewXFileContainer.Rows(indexRow).Selected = True
            dataGridViewXFileContainer.FirstDisplayedScrollingRowIndex = indexRow
        End If

        dataGridViewXFileContainer.DataSource = query
        dataGridViewXFileContainer.Columns("ID_Cont").Visible = False
        'dataGridViewXFileContainer.Columns("tblFile").Visible = False
    End Sub
#End Region

    ''' <summary>
    ''' Lưu thông tin hiển thị trên form vào các object cụ thể
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub GetInfoByForm()
        With _objCont
            Try
                If dtHaCont.Value = "#12:00:00 AM#" Then
                    .GetEmptyContDate = Nothing
                Else
                    .GetEmptyContDate = dtHaCont.Value
                End If
            Catch ex As Exception
                .GetEmptyContDate = Nothing
            End Try

            Try
                If dtNangCont.Value = "#12:00:00 AM#" Then
                    .ReturnContDate = Nothing
                Else
                    .ReturnContDate = dtNangCont.Value
                End If
            Catch ex As Exception
                .ReturnContDate = Nothing
            End Try

            Try
                .ID_DemDet = cmbKhoDongGiaoHang.SelectedValue
            Catch ex As Exception
                .tblDemDet = cmbKhoDongGiaoHang.SelectedItem
            End Try

            Try
                .ID_Driver = cmbDriver.SelectedValue
            Catch ex As Exception
                .tblDriver = cmbDriver.SelectedItem
            End Try
        End With
    End Sub

#Region "Commands"
    ''' <summary>
    ''' Init commands
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub InitCommands()
        '_ucCommands = New ucCommands(Me)
        _ucCommands.InitControl(Me)
        _ucCommands.ShowHideButtons(False, True, False, False)
        '_ucCommands.btnAddEvent_Click = New EventHandler(AddressOf btnAdd_Click)
        _ucCommands.btnEditEvent_Click = New EventHandler(AddressOf btnEdit2_Click)
        _ucCommands.btnDeleteEvent_Click = New EventHandler(AddressOf btnDel2_Click)
        _ucCommands.btnUpdateEvent_Click = New EventHandler(AddressOf btnUpdate2_Click)
        _ucCommands.btnCancelEvent_Click = New EventHandler(AddressOf btnCancel2_Click)
        _ucCommands.Dock = DockStyle.Fill
        PanelExCommand.Controls.Add(_ucCommands)
    End Sub


    Public Sub FocusControl()
        cmbDriver.Focus()
    End Sub

    Private Sub ReadOnlyControls()
        txtContNo.ReadOnly = True
    End Sub
    'Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    'End Sub

    Private Sub btnEdit2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ReadOnlyControls()
        FocusControl()
    End Sub

    Private Sub btnUpdate2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            'Lưu thông tin trên form vào object
            '_objFileMBL = GetInfoByForm()
            GetInfoByForm()
            Dim action As enumAction
            'Lưu current row index hiện tại
            Dim indexRow As Integer = -1
            'Nếu tồn tại ID_FileMBL thì cập nhật
            If _objCont.ID_Cont > 0 Then
                _objContController.UpdateRecordWithoutAttach(_objCont)
                action = enumAction.Edit
                indexRow = dataGridViewXFileContainer.CurrentRow.Index
            Else 'Không tồn tại thì thêm mới
                _objContController.InsertRecord(_objCont)
                action = enumAction.Add
                indexRow = dataGridViewXFileContainer.Rows.Count
            End If
            'Write log
            Dim objLogController As New LogController
            objLogController.Insert(action, String.Format("Container Transport (Cont# {0}) of File {1}", _objCont.ContNo, _objFile.FileNo))

            'Refresh gridview
            BindingDataGridView(_objFile, indexRow)
            'Set current row
            '_ucGridView.DataGridView.Rows(indexRow).Selected = True
            'Refresh buttons
            ReadOnlyControls()
        Catch ex As Exception
#If DEBUG Then
            Throw ex
#Else
                    MessageBox.Show(ex.Message)
#End If
        End Try
    End Sub

    Private Sub btnDel2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'If MessageBox.Show("Bạn thật sự muốn xóa dữ liệu này?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
        '    Dim indexRow As Integer = _ucGridView.DataGridView.CurrentRow.Index - 1
        '    _objFileMBLController.Delete(_objFileMBL)
        '    _ucGridView.BindingDataGridView(_objFile, indexRow)
        '    'MessageBox.Show("Complete!")
        'End If
    End Sub

    Private Sub btnCancel2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ReadOnlyControls()
        dataGridViewXFileContainer_CurrentCellChanged(Nothing, Nothing)
    End Sub
#End Region

#Region "Sy"
    'Dim db As New TanNamChinhDataContext
    'Private m_ID_Cont As Integer = 0

    'Public Sub KhoiTaodtgContFee(ByVal ID_Cont As Integer)
    '    'Kiem tra ton tai trong tblContFee chưa?
    '    'Neu chua Insert các loại phí Transport vào tblContFee
    '    Dim c_contfee = (From p In db.tblContFees
    '                     Where p.ID_Cont = ID_Cont
    '                     Select p).Count
    '    If c_contfee = 0 Then
    '        Dim fee_transport = From p In db.tblFees
    '                            Where p.ID_FeeType = 3
    '                            Select p

    '        For Each fee As tblFee In fee_transport
    '            Dim cont_fee As New tblContFee
    '            cont_fee.ID_Cont = ID_Cont
    '            cont_fee.ID_Fee = fee.ID_Fee
    '            cont_fee.Price = 0
    '            db.tblContFees.InsertOnSubmit(cont_fee)
    '            db.SubmitChanges()
    '        Next

    '    End If

    '    Dim contFee = From p In db.tblContFees
    '                 Where p.ID_Cont = ID_Cont
    '                 Select New With {p.ID_ContFee, p.ID_Fee, p.ID_Payee, p.tblFee.FeeName, p.Price, p.InvoiceNo, p.Description}

    '    dtgContFee.DataSource = contFee

    '    FormatdtgContFee()
    '    'Tinh TongTien theo Cont
    '    Dim TongTien As Double = 0

    '    For i As Integer = 0 To dtgContFee.RowCount - 1
    '        TongTien += dtgContFee.Rows(i).Cells("Price").Value
    '    Next
    '    lblTotal.Text = TongTien.ToString("#,###")
    'End Sub

    'Public Sub FormatdtgContFee()
    '    dtgContFee.RowHeadersWidth = 20
    '    dtgContFee.RowHeadersDefaultCellStyle.ForeColor = Color.Blue
    '    'dtgContFee.RowTemplate.Height = 25

    '    dtgContFee.MultiSelect = False
    '    dtgContFee.SelectionMode = DataGridViewSelectionMode.FullRowSelect
    '    'dtgContFee.ReadOnly = True
    '    dtgContFee.BackgroundColor = Color.White
    '    dtgContFee.AllowUserToAddRows = False
    '    dtgContFee.AllowUserToDeleteRows = False

    '    dtgContFee.Columns("ID_ContFee").Visible = False
    '    dtgContFee.Columns("ID_Fee").Visible = False
    '    dtgContFee.Columns("ID_Payee").Visible = False

    '    'dtgContFee.Columns("ID_Cont").Visible = False
    '    'dtgContFee.Columns("ID_AdvanceVoucher").Visible = False
    '    'dtgContFee.Columns("ID_ReceiptVoucher").Visible = False
    '    'dtgContFee.Columns("ID_PaymentVoucher").Visible = False
    '    'dtgContFee.Columns("DriverName").Visible = False
    '    'dtgContFee.Columns("ID_FeeType").Visible = False
    '    'dtgContFee.Columns("FeeAbbreviated").Visible = False
    '    'dtgContFee.Columns("PhoneNo").Visible = False
    '    'dtgContFee.Columns("Address").Visible = False
    '    'dtgContFee.Columns("ID_Manager").Visible = False

    '    With dtgContFee.Columns("Price")
    '        .HeaderText = "Số tiền"
    '        .Width = 100
    '        .DefaultCellStyle.Format = "#,###"
    '        .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
    '    End With
    '    With dtgContFee.Columns("InvoiceNo")
    '        .HeaderText = "Số hóa đơn"
    '        .Width = 100
    '    End With
    '    With dtgContFee.Columns("Description")
    '        .HeaderText = "Ghi chú"
    '        .Width = 100
    '    End With
    '    With dtgContFee.Columns("FeeName")
    '        .HeaderText = "Loại phí"
    '        .Width = 150
    '        .ReadOnly = True
    '    End With
    'End Sub

    'Private Sub AddComboBoxColumns()
    '    Dim comboboxColumn As DataGridViewComboBoxColumn
    '    comboboxColumn = CreateComboBoxColumn()
    '    SetAlternateChoicesUsingDataSource(comboboxColumn)
    '    comboboxColumn.HeaderText = "Người đóng tiền"
    '    dtgContFee.Columns.Add(comboboxColumn)

    '    'comboboxColumn = CreateComboBoxColumn()
    '    'SetAlternateChoicesUsingItems(comboboxColumn)
    '    'comboboxColumn.HeaderText = _
    '    '    "TitleOfCourtesy (via Items property)"
    '    '' Tack this example column onto the end.
    '    'DataGridView1.Columns.Add(comboboxColumn)
    'End Sub

    'Private Function CreateComboBoxColumn() As DataGridViewComboBoxColumn
    '    Dim column As New DataGridViewComboBoxColumn()

    '    With column
    '        .DataPropertyName = "ID_Payee"
    '        .HeaderText = "Người đóng tiền"
    '        .DropDownWidth = 160
    '        .Width = 120
    '        .MaxDropDownItems = 3
    '        .FlatStyle = FlatStyle.Flat
    '    End With
    '    Return column
    'End Function

    'Private Sub SetAlternateChoicesUsingDataSource(ByVal comboboxColumn As DataGridViewComboBoxColumn)
    '    Dim driver = From p In db.tblDrivers
    '                   Select p
    '    With comboboxColumn
    '        .DataSource = driver
    '        .ValueMember = "ID_Driver"
    '        .DisplayMember = "DriverName"
    '    End With
    'End Sub

    'Public Function TaoColumscbb(ByVal colName As String) As DataGridViewComboBoxColumn
    '    Dim driver = From p In db.tblDrivers
    '                   Select p
    '    Dim cbbDriver As New DataGridViewComboBoxColumn
    '    cbbDriver.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
    '    cbbDriver.Name = colName
    '    cbbDriver.HeaderText = "Người đóng phí"
    '    cbbDriver.DataSource = driver
    '    cbbDriver.DisplayMember = "DriverName"
    '    cbbDriver.ValueMember = "ID_Driver"
    '    Return cbbDriver
    'End Function

    'Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveCharges.Click
    '    'Update tblConFee
    '    Dim TongTien As Double = 0

    '    For i As Integer = 0 To dtgContFee.RowCount - 1
    '        TongTien += dtgContFee.Rows(i).Cells("Price").Value
    '        Dim ID_ContFee As Integer
    '        ID_ContFee = dtgContFee.Rows(i).Cells("ID_ContFee").Value

    '        Dim contfee = (From p In db.tblContFees
    '                   Where p.ID_ContFee = ID_ContFee
    '                   Select p).Single

    '        contfee.ID_Payee = dtgContFee.Rows(i).Cells("ID_Payee").Value
    '        contfee.InvoiceNo = dtgContFee.Rows(i).Cells("InvoiceNo").Value
    '        contfee.Price = dtgContFee.Rows(i).Cells("Price").Value
    '        contfee.Description = dtgContFee.Rows(i).Cells("Description").Value

    '        db.SubmitChanges()
    '    Next

    '    MsgBox("Đã lưu vào dữ liệu")
    '    btnEditCharges.Enabled = True
    '    btnSaveCharges.Enabled = False
    '    btnCancelCharges.Enabled = False
    '    dtgContFee.ReadOnly = True
    '    KhoiTaodtgContFee(m_ID_Cont)
    'End Sub

    'Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditCharges.Click
    '    btnSaveCharges.Enabled = True
    '    btnCancelCharges.Enabled = True
    '    btnEditCharges.Enabled = False
    '    dtgContFee.ReadOnly = False
    'End Sub

    'Private Sub btncancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelCharges.Click
    '    btnEditCharges.Enabled = True
    '    btnSaveCharges.Enabled = False
    '    btnCancelCharges.Enabled = False
    '    dtgContFee.ReadOnly = True
    '    KhoiTaodtgContFee(m_ID_Cont)
    'End Sub
#End Region
    'Sỹ code
    Dim uc As ucTransportFee = Nothing

    Private Sub TabControl1_SelectedTabChanged(ByVal sender As Object, ByVal e As DevComponents.DotNetBar.TabStripTabChangedEventArgs) Handles TabControl1.SelectedTabChanged
        Try
            Dim ID_Cont As Integer = 0
            ID_Cont = _objCont.ID_Cont
            If uc Is Nothing Then
                uc = New ucTransportFee(ID_Cont)
                uc.Dock = DockStyle.Fill
                PanelExContFee.Controls.Add(uc)
            Else
                uc.KhoiTaodtgContFee(ID_Cont)
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub cmbDriver_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbDriver.SelectedIndexChanged
        If cmbDriver.SelectedValue Then
            txtNguoiDongTienHa.Text = cmbDriver.Text
        End If
    End Sub
End Class
